import React, { Component } from "react";

import { SearchBar } from "antd-mobile";

import { getCity } from "../../../utils/city";

import { API } from "../../../utils/api";

import styles from "./index.module.css";

export default class Search extends Component {
  // 当前城市id
  cityId = getCity().value;
  timeId = null
  state = {
    // 搜索框的值
    searchTxt: "",
    tipsList: []
  };

  // 渲染搜索结果列表
  renderTips = () => {
    const { tipsList } = this.state;

    return tipsList.map(item => (
      <li key={item.community} className={styles.tip} onClick={()=>this.tipsClick(item)}>
        {item.communityName}
      </li>
    ));
  };
  tipsClick = (item) => {
    const {history} = this.props
    history.replace('/rent/add',{
      name: item.communityName,
      id: item.community
    })
  }
  onChange = val => {
    // 变化的值
    this.setState(() => {
      return {
        searchTxt: val
      };
    });
    if (!val) {
      return this.setState(() => {
        return {
          tipsList: []
        };
      });
    } else {
      // 获取小区数据

      clearTimeout(this.timeId);
      this.timeId = setTimeout(async () => {
        const { data: res } = await API.get(`/area/community`, {
          params: {
            name: val,
            id: this.cityId
          }
        });
        this.setState(() => {
          return {
            tipsList: res.body
          };
        });
      }, 500);
    }
  };
  render() {
    const { history } = this.props;
    const { searchTxt } = this.state;

    return (
      <div className={styles.root}>
        {/* 搜索框 */}
        <SearchBar
          placeholder="请输入小区或地址"
          value={searchTxt}
          showCancelButton={true}
          onCancel={() => history.replace("/rent/add")}
          onChange={this.onChange}
        />

        {/* 搜索提示列表 */}
        <ul className={styles.tips}>{this.renderTips()}</ul>
      </div>
    );
  }
}
